<template>
    <basic-container>
        <el-form ref="queryForm"
                 :model="queryParams"
                 :inline="true"
                 label-width="80px">
            <el-form-item label="用户名称"
                          prop="searchParams.search_eq_realName">
                <el-input v-model="queryParams.searchParams.search_eq_realName"
                          placeholder="请输入用户名称"/>
            </el-form-item>
            <el-form-item label="登录账号"
                          prop="searchParams.search_eq_account">
                <el-input v-model="queryParams.searchParams.search_eq_account"
                          placeholder="请输入登录账号"/>
            </el-form-item>
            <el-form-item label="身份证号"
                          prop="searchParams.search_eq_idCard">
                <el-input v-model="queryParams.searchParams.search_eq_idCard"
                          placeholder="请输入身份证号"/>
            </el-form-item>
            <el-form-item label="联系方式"
                          prop="searchParams.search_eq_phone">
                <el-input v-model="queryParams.searchParams.search_eq_phone"
                          placeholder="请输入联系方式"/>
            </el-form-item>
            <el-form-item label="使用状态"
                          prop="searchParams.search_eq_start">
                <el-select v-model="queryParams.searchParams.search_eq_start" placeholder="请选择">
                    <el-option
                            v-for="dict in statusOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary"
                           icon="el-icon-search"
                           size="mini"
                           @click="handleQuery">搜索
                </el-button>
                <el-button icon="el-icon-refresh"
                           size="mini"
                           @click="resetQuery">重置
                </el-button>
            </el-form-item>
        </el-form>


        <el-row :gutter="10"
                class="mb8">
            <el-col :span="1.5">
                <el-button type="primary"
                           icon="el-icon-plus"
                           size="mini"
                           @click="handleAdd"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        icon="el-icon-edit"
                        size="mini"
                        :disabled="single"
                        @click="handleUpdate"
                >编辑
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        icon="el-icon-delete"
                        size="mini"
                        :disabled="multiple"
                        @click="handleDelete"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        icon="el-icon-download"
                        size="mini"
                >导出
                </el-button>
            </el-col>
        </el-row>
        <el-table v-loading="loading"
                  :data="userList"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="登录账号" align="center" prop="account"/>
            <el-table-column label="用户名" align="center" prop="realName"/>
            <el-table-column label="所属部门" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.deptName">{{scope.row.deptName}}</span>
                    <span v-else>/</span>
                </template>
            </el-table-column>
            <el-table-column label="身份证号" align="center" prop="idCard"/>
            <el-table-column label="联系电话" align="center" prop="phone">
                <template slot-scope="scope">
                    <span v-if="scope.row.phone">{{scope.row.phone}}</span>
                    <span v-else>/</span>
                </template>
            </el-table-column>
            <el-table-column label="年龄" align="center" prop="age">
                <template slot-scope="scope">
                    <span v-if="scope.row.age">{{scope.row.age}}</span>
                    <span v-else>/</span>
                </template>
            </el-table-column>
            <el-table-column label="性别" align="center" prop="sex" :formatter="sexFormat">
            </el-table-column>
            <el-table-column label="使用状态"
                             align="center">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.start"
                               :active-value="0"
                               :inactive-value="1"
                               @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作"
                             align="center"
                             class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button-group>
                        <el-button size="small"
                                   type="text"
                                   icon="el-icon-edit"
                                   @click="handleUpdate(scope.row)"
                        >编辑
                        </el-button>
                        <el-button size="small"
                                   type="text"
                                   icon="el-icon-delete"
                                   class="deleteBtn"
                                   @click="handleDelete(scope.row)"
                        >删除
                        </el-button>
                        <el-button size="small"
                                   type="text"
                                   icon="el-icon-help"
                                   class="deleteBtn"
                                   @click="resetPass(scope.row)"
                        >重置密码
                        </el-button>


                    </el-button-group>

                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>


        <!-- 添加或编辑收费员信息对话框 -->
        <el-dialog :title="title[statusDialog]"
                   :visible.sync="open"
                   width="60%"
                   append-to-body
                   :close-on-click-modal="false">
            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户名"
                                      prop="realName">
                            <el-input v-model="form.realName"
                                      placeholder="请输入姓名"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所属部門"
                                      prop="deptId">
                            <treeselect v-model="form.deptId" :multiple="false" placeholder="请选择归属部门"
                                        :options="deptOptions" :normalizer="normalizer" @select="updateInput"/>
                        </el-form-item>

                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="身份证号"
                                      prop="idCard">
                            <el-input v-model="form.idCard"
                                      :maxlength="18"
                                      placeholder="请输入身份证号"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用户电话"
                                      prop="phone">
                            <el-input v-model="form.phone"
                                      placeholder="请输入电话"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户性别">
                            <el-radio-group v-model="form.sex">
                                <el-radio v-for="dict in sexOptions"
                                          :key="dict.dictValue"
                                          :label="dict.dictValue">{{dict.dictLabel}}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用户年龄"
                                      prop="age">
                            <el-input v-model="form.age"
                                      placeholder="请输入年龄"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="登录账号"
                              prop="account">
                    <el-input v-model="form.account"
                              placeholder="请输入登录账号"/>
                </el-form-item>

                <el-form-item label="登录密码"
                              prop="password">
                    <el-input type="password"
                              v-model="form.password"
                              placeholder="请输入登录密码"/>
                </el-form-item>
                <el-form-item label="拥有角色" prop="roles">
                    <el-select v-model="form.roles"
                               multiple
                               placeholder="请选择" style="width: 100%">
                        <el-option v-for="item in roleOptions"
                                   :key="item.id"
                                   :label="item.name"
                                   :value="item.id"
                                   :disabled="item.status == 1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="使用状态">
                    <el-radio-group v-model="form.start">
                        <el-radio v-for="dict in statusOptions"
                                  :key="dict.dictValue"
                                  :label="dict.dictValue">{{dict.dictLabel}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <div slot="footer"
                 class="dialog-footer">
                <el-button type="primary"
                           @click="submitForm">确 定
                </el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


    </basic-container>
</template>

<script>
    import {mapGetters} from "vuex";
    import {addUser, delUser, listDept, listRole, listUser, reset, startUser, updateUser} from "@/api/system/user";

    export default {
        data() {
            return {
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 总条数
                total: 0,
                // 用户信息表格数据
                userList: [],
                // 弹出层标题
                title: {
                    add: '新增用户',
                    edit: '编辑用户'
                },
                statusDialog: "",
                // 是否显示弹出层
                open: false,
                statusOptions: [],
                sexOptions: [],
                roleOptions: [],
                roleIds: [],
                deptOptions: [],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    searchParams: {
                        search_eq_realName: undefined,
                        search_eq_idCard: undefined,
                        search_eq_phone: undefined,
                        search_eq_account: undefined,
                        search_eq_start: undefined,
                    }
                },
                // 表单参数
                form: {},
                // 表单校验
                rules: {
                    realName: [
                        {required: true, message: "姓名不能为空", trigger: "blur"}
                    ],
                    sex: [
                        {required: true, message: "性别不能为空", trigger: "blur"}
                    ],
                    idCard: [
                        {required: true, message: "身份证号不能为空", trigger: "blur"},
                        {
                            validator: (rule, value, callback) => {
                                if (value) {
                                    if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
                                        callback(new Error("请输入正确的号码！"));
                                    } else {
                                        callback();
                                    }
                                } else {
                                    callback();
                                }
                            },
                            trigger: "blur"
                        }
                    ],
                    age: [
                        {required: true, message: "年龄不能为空", trigger: "blur"},
                        {
                            validator: (rule, value, callback) => {
                                if (value) {
                                    if (!/(^[1-9]\d*$)/.test(value)) {
                                        callback(new Error("请输入大于零的正整数值"));
                                    } else {
                                        callback();
                                    }
                                } else {
                                    callback();
                                }
                            },
                            trigger: "blur"
                        }
                    ],
                    phone: [
                        {required: true, message: "电话不能为空", trigger: "blur"},
                        {
                            validator: (rule, value, callback) => {
                                if (value) {
                                    if (!/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)) {
                                        callback(new Error("请输入正确的电话号码！"));
                                    } else {
                                        callback();
                                    }
                                } else {
                                    callback();
                                }
                            },
                            trigger: "blur"
                        }
                    ],
                    account: [
                        {required: true, message: "登录账号不能为空", trigger: "blur"}
                    ],
                    password: [
                        {required: true, message: "登录密码不能为空", trigger: "blur"}
                    ],
                    start: [
                        {required: true, message: "状态不能为空", trigger: "blur"}
                    ],
                    deptId: [
                        {required: true, message: "部门不能为空", trigger: "blur"}
                    ],
                    roles: [
                        {required: true, message: "角色不能为空", trigger: "blur"}
                    ],
                }

            }

        },
        created() {
            this.getList();
            this.getListDept();
            this.getDicts("sys_status").then(response => {
                this.statusOptions = response.data.data;
            });
            this.getDicts("sys_sex").then(response => {
                this.sexOptions = response.data.data;
            });
        },
        computed: {
            ...mapGetters(["userInfo"])
        },
        methods: {
            /** 搜索按钮操作 */
            handleQuery() {
                for (let key in this.queryParams.searchParams) {
                    if(this.queryParams.searchParams[key]!=undefined){
                        if (this.queryParams.searchParams[key] == "") {
                            this.queryParams.searchParams[key] = undefined;
                            continue;
                        }
                        if(this.queryParams.searchParams[key].length>0){
                            if(!this.queryParams.searchParams[key].constructor == Array){
                                if(!(this.queryParams.searchParams[key].replace(" ", "").trim().length > 0)){
                                    this.queryParams.searchParams[key] = undefined;
                                    continue;
                                }
                            }
                        }
                    }
                }
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    realName: undefined,
                    idCard: undefined,
                    sex: "0",
                    age: undefined,
                    phone: undefined,
                    account: undefined,
                    password: '123456',
                    deptId: undefined,
                    deptName: undefined,
                    start: "0",
                    roles: undefined,
                    delFlag: undefined,
                    createTime: undefined,
                    createBy: undefined,
                    updateTime: undefined,
                    updateBy: undefined
                };
                this.resetForm("form");
            },
            normalizer(node) {
                //去掉children=null的属性
                if (node.children == null || node.children == 'null') {
                    delete node.children;
                }
                return {
                    id: node.id,
                    label: node.name,
                    children: node.children,
                }

            },
            /** 查询收费员信息列表 */
            getList() {
                this.loading = true;
                listUser(this.queryParams).then(response => {
                    const data = response.data;
                    if (response.status === 200 && data.code === "00") {
                        this.userList = data.data.rows;
                        this.total = data.data.total;
                    } else {
                        this.msgError(data.msg);
                    }
                    this.loading = false;
                });
            },
            getListDept() {
                listDept().then(response => {
                    const data = response.data.data;
                    this.deptOptions = this.handleTree(data);
                });
            },
            getListRole(id) {
                let json = {act: this.statusDialog, userId: id};
                listRole(json).then(response => {
                    const data = response.data.data;
                    this.roleOptions = data.roles;
                    if (data.users != null) {
                        this.form.roles = data.users;
                    }
                });
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                // this.ids = selection.map(item => item.id)
                this.ids = selection;
                this.single = selection.length != 1;
                this.multiple = !selection.length;
            },
            updateInput(value) {
                this.form.deptName = undefined;
                this.form.deptName = value.name;
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.statusDialog = 'add';
                this.getListRole(0);
            },
            /** 编辑按钮操作 */
            handleUpdate(row) {
                if (row.id) {
                    this.form = JSON.parse(JSON.stringify(row));
                } else {
                    this.form = JSON.parse(JSON.stringify(this.ids[0]));
                }
                this.form.deptId = this.form.deptId + "";
                this.form.sex = this.form.sex + "";
                this.form.start = this.form.start + "";
                this.open = true;
                this.statusDialog = 'edit';
                this.getListRole(this.form.id);
            },
            /** 提交按钮 */
            submitForm: function () {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.id != undefined) {
                            updateUser(this.form).then(response => {
                                const data = response.data;
                                if (response.status === 200 && data.code === "00") {
                                    this.msgSuccess("编辑成功");
                                    this.open = false;
                                    this.getList();
                                } else {
                                    this.msgError(response.msg);
                                }
                            });
                        } else {
                            addUser(this.form).then(response => {
                                const data = response.data;
                                if (response.status === 200 && data.code === "00") {
                                    this.msgSuccess("新增成功");
                                    this.open = false;
                                    this.getList();
                                } else {
                                    this.msgError(response.msg);
                                }
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const userIds = row.id || this.ids;
                this.$confirm('是否确认删除为"' + row.realName + '"的数据项?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return delUser(userIds);
                }).then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                }).catch(function () {
                });
            },
            /** 重置密码按钮操作 */
            resetPass(row) {
                const userIds = row.id;
                this.$confirm('是否确认重置为"' + row.realName + '"的密码吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return reset(userIds);
                }).then(() => {
                    this.getList();
                    this.msgSuccess("重重成功");
                }).catch(function () {
                });
            },
            // 用户状态编辑
            handleStatusChange(row) {
                startUser(row).then(response => {
                    let msg = response.data.msg;
                    this.msgSuccess(msg);
                });
            },
            sexFormat(row) {
                return this.selectDictLabel(this.sexOptions, row.sex);
            }
        }
    };
</script>

<style>

</style>
